<template>
  <div >
    <!--导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/user/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>计划管理</el-breadcrumb-item>
      <el-breadcrumb-item>创建计划</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
    <el-row :gutter="20">
      <el-col :span="4">
        <div >
          <div class="crumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>
                <el-button type="primary" size="mini" @click="getUserGroup()">创建计划</el-button>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-tree  accordion :data="data"  :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="grid-content bg-purple">
          <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
            <el-tab-pane label="周计划" name="first">
              <el-table border :data="weekPlanInfo" style="width: 100%">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="计划标题" prop="planName"></el-table-column>
                <el-table-column label="负责人" prop="userName"></el-table-column>
                <el-table-column label="计划状态">
                  <template slot-scope="scope">
                    <el-button v-show="scope.row.planStatus == '进行中'" size="mini" type="warning" plain
                               class="buttonStatus" @click="changeStatus(scope.row.planId)">
                      进行中
                    </el-button>
                    <el-button v-show="scope.row.planStatus == '未完成'" size="mini" type="danger" plain>
                      未完成
                    </el-button>
                    <el-button v-show="scope.row.planStatus == '已完成'" size="mini" type="success" plain>
                      已完成
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="开始时间" sortable>
                  <template slot-scope="scope">
                    <span style="margin-left: 10px;color:#67C23A"><i class="el-icon-time"></i>{{scope.row.startTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="截止时间" sortable>
                  <template slot-scope="scope">
                    <span style="margin-left: 10px;color: red"><i class="el-icon-time"></i>{{scope.row.endTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="270">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleShow(scope.row.planStatus,scope.row.planDesc,scope.row.planSummary)">
                      查看计划
                    </el-button>
                    <el-button size="mini" type="primary" v-show="scope.row.planStatus == '已完成' || scope.row.planStatus == '未完成'"
                     @click="addSummary(scope.row.planId,scope.row.planSummary)">
                           {{scope.row.planSummary ? '修改总结':'添加总结'}}
                    </el-button>
                    <el-button size="mini" v-show="scope.row.planStatus == '进行中'" type="success"
                          @click="showEditDialog(scope.row.planId,scope.row.username,scope.row.planDesc,scope.row.planName,scope.row.startTime,scope.row.endTime)">
                      修改计划
                    </el-button>
                    <el-button size="mini" type="danger" v-show="scope.row.planStatus === '进行中'" @click="deletePlan(scope.row.planId)">
                      删除
                    </el-button>
                  </template>

                </el-table-column>
              </el-table>
              <!--分页-->
              <el-pagination
                @size-change="weekHandleSizeChange"
                @current-change="weekHandleCurrentChange"
                :current-page="weekPage.pageNum"
                :page-sizes="[6,7, 8, 9, 10]"
                :page-size="weekPage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="weekPage.total">
              </el-pagination>
            </el-tab-pane>
            <el-tab-pane label="月计划" name="second">
              <el-table border style="width: 100%" :data="monthPlanInfo">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="计划标题" prop="planName"></el-table-column>
                <el-table-column label="负责人" prop="userName"></el-table-column>
                <el-table-column label="计划状态">
                  <template slot-scope="scope">
                    <el-button v-show="scope.row.planStatus == '进行中'" size="mini" type="warning" plain
                               class="buttonStatus" @click="changeStatus(scope.row.planId)">
                      进行中
                    </el-button>
                    <el-button v-show="scope.row.planStatus == '未完成'" size="mini" type="danger" plain>
                      未完成
                    </el-button>
                    <el-button v-show="scope.row.planStatus == '已完成'" size="mini" type="success" plain>
                      已完成
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="开始时间" sortable>
                  <template slot-scope="scope">
                    <span style="margin-left: 10px;color:#67C23A"><i class="el-icon-time"></i>{{scope.row.startTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="截止时间" sortable>
                  <template slot-scope="scope">
                    <span style="margin-left: 10px;color: red"><i class="el-icon-time"></i>{{scope.row.endTime}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="270">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleShow(scope.row.planStatus,scope.row.planDesc,scope.row.planSummary)">
                      查看计划
                    </el-button>
                    <el-button size="mini" type="primary" v-show="scope.row.planStatus == '已完成' || scope.row.planStatus == '未完成'"
                               @click="addSummary(scope.row.planId)">
                      {{scope.row.planSummary ? '修改总结':'添加总结'}}
                    </el-button>
                    <el-button size="mini" v-show="scope.row.planStatus == '进行中'" type="success"
                               @click="showEditDialog(scope.row.planId,scope.row.username,scope.row.planDesc,scope.row.planName,scope.row.startTime,scope.row.endTime)">
                      修改计划
                    </el-button>
                    <el-button size="mini" type="danger" v-show="scope.row.planStatus === '进行中'" @click="deletePlan(scope.row.planId)">
                      删除
                    </el-button>
                  </template>

                </el-table-column>
              </el-table>
              <!--分页-->
              <el-pagination
                @size-change="monthHandleSizeChange"
                @current-change="monthHandleCurrentChange"
                :current-page="monthPage.pageNum"
                :page-sizes="[8,9, 10, 11, 12]"
                :page-size="monthPage.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="monthPage.total">
              </el-pagination>
            </el-tab-pane>
          </el-tabs >
        </div>
      </el-col>
    </el-row>

    <!--计划详情-->
    <el-drawer :visible.sync="drawer" :direction="direction">
      <p style="text-align:center;font-size:20px;font-weight:bold" >计划内容</p><br>
      <el-input type="textarea" class="sideBarPlanDesc" :show-word-limit="true"
                v-model="sideBarPlanDesc" autosize>
      </el-input>
      <p style="text-align:center;font-size:20px;font-weight:bold" >计划总结</p><br>
      <el-input type="textarea" class="sideBarPlanDesc" :show-word-limit="true"
                autosize :value="sideBarPlanSummary ? sideBarPlanSummary :'暂未填写该计划的总结'">
      </el-input>
    </el-drawer>
    <!--新建计划弹窗-->
    <el-dialog title="新建计划" :visible.sync="dialogNewTreeVisible" width="30%" @close="dialogClear">
      <el-form ref="createForm" :model="createPlanForm" label-width="120px" :rules="planRules">
        <el-form-item  label="计划类型" prop="planType">
          <el-select  v-model="createPlanForm.planType"  placeholder="请选择计划类型">
            <el-option v-for="item of planTypeList" :key="item.index" :label="item.typeName"  :value="item.typeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="选择项目组" prop="groupName">
          <el-select v-model="createPlanForm.groupName"  placeholder="请选择项目组" @change="getUserNameByGroupName()">
            <el-option v-for="item of groupList" :key="item.index" :label="item.groupName"  :value="item.groupName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="计划负责人" prop="userNames">
          <el-select  v-model="createPlanForm.userNames"  multiple placeholder="请选择负责人">
            <el-option
              v-for="item in personList"
              :key="item.userName"
              :label="item.userName"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-col  :span="11">
            <el-date-picker  type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="开始时间" v-model="createPlanForm.startTime"
                              size="small" @change="calculationEndTime">
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="截止时间">
          <el-col  :span="11">
            <el-date-picker  type="date" placeholder="开始时间" v-model="createPlanForm.endTime"  format="yyyy-MM-dd"
                             value-format="yyyy-MM-dd" size="small" disabled>
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="计划标题" prop="planTitle">
          <el-input placeholder="请输入计划标题"  v-model="createPlanForm.planTitle"></el-input>
        </el-form-item>
        <el-form-item label="计划内容" prop="planDesc">
          <el-input placeholder="请输入计划内容" type="textarea" v-model="createPlanForm.planDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPlan()">立即创建</el-button>
          <el-button @click="dialogNewTreeVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--修改计划内容-->
    <el-dialog title="修改计划内容" :visible.sync="editPlanDialog" width="25%" center>
      <el-form label-width="80px">
        <el-form-item label="标题:">
          <el-input size="small" v-model="editPlanForm.planName"></el-input>
        </el-form-item>
        <div v-show="editMonthShow" >
          <el-form-item label="开始时间">
            <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请输入开始日期"  v-model="editPlanForm.editPlanStartTime" :value="editPlanForm.editPlanStartTime"></el-date-picker>
          </el-form-item>
          <el-form-item label="截止时间">
            <el-date-picker type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="请输入截止日期" v-model="editPlanForm.editPlanEndTime" :value="editPlanForm.editPlanEndTime"></el-date-picker>
          </el-form-item>
        </div>
        <el-form-item  label="计划内容:">
          <el-input type="textarea" v-model="editPlanForm.editPlanDesc"
                    :autosize="{ minRows: 4, maxRows: 6}">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitEditPlan()" size="small">立即修改</el-button>
          <el-button @click="editPlanDialog = false" size="small">取消</el-button>
      </span>
    </el-dialog>
    </el-card>
  </div>
</template>
<script>
  export default {
    name: 'CreatePlan',
    data() {
      return {
        dialogNewTreeVisible:false,//创建计划弹窗
        drawer: false,
        activeName: 'first',//选项卡
        direction: 'rtl',//设置查看计划右边弹窗
        data:[], //树形结构的数据
        weekPlanInfo: [], //周计划
        monthPlanInfo: [], //月计划
        editPlanDialog: false,//修改计划dialog
        editMonthShow: false, //月计划允许修改日期
        editPlanForm: {
          editPlanStartTime: '',
          editPlanEndTime: '',
          editPlanDesc: '',
          planId: '',
          planName: ''
        },
        //计划类型：周计划、月计划
        planTypeList: [
          {
            typeName: '周计划'
          },
          {
            typeName: '月计划'
          }
        ],
        sideBarPlanDesc: '',
        sideBarPlanSummary: '暂未填写该计划总结',
        showSummary: false,
        isUpdateSummary: false,
        //周计划页码
        weekPage: {
          //当前的页数
          pageNum: 1,
          //每页显示多少条数据
          pageSize: 6,
          //总条数
          total: 1
        },
        //月计划页码
        monthPage: {
          //当前的页数
          pageNum: 1,
          //每页显示多少条数据
          pageSize: 6,
          //总条数
          total: 1
        },
        //新建计划的表单属性
        createPlanForm:{
          planType: '',
          groupName: '',
          userNames: [],
          startTime: '',
          endTime: '',
          planTitle: '',
          planDesc: ''
        },
        groupList: [],
        personList: [],
        defaultProps:{
          children: 'children',
          label: 'label'
        },
        //表单数据验证
        planRules: {
          planType: [
            { required: true, message: '请选择计划类型', trigger: 'change' }
          ],
          groupName: [
            { required: true, message: '请选组名', trigger: 'change' }
          ],
          userNames: [
            { required: true, message: '请选负责人', trigger: 'change' }
          ],
          startTime: [
            { required: true, message: '请选开启时间', trigger: 'change' }
          ],
          planTitle: [
            { required: true, message: '请填写计划标题', trigger: 'blur' }
          ],
          planDesc: [
            { required: true, message: '请填写计划说明', trigger: 'blur' }
          ]
        }
      };
    },
    created() {
      this.getPlanTree();
    },
    methods:{
      //从后端获取树形数据并渲染
      async getPlanTree(){
        var userInformation = JSON.parse(window.sessionStorage.getItem("user"));
        const {data: res} = await this.$http.get(`plan/getPlanTreeData/${userInformation.userId}`);
        if (res.status !== 200){
          return this.$message.error("获取树形数据失败");
        }
        this.data = res.data;
        console.log(res);
      },
      //获取当前用户的所属组
      async getUserGroup(){
        this.dialogNewTreeVisible = true;
        var userInformation = JSON.parse(window.sessionStorage.getItem("user"));
        const {data: res} = await this.$http.get(`group/getMyGroups/${userInformation.userId}`);
        console.log(res);
        if (res.status !== 200){
          return this.$message.error("获取组数据失败！");
        }
        this.groupList = res.data;
      },
      //根据组名获取用户名
      async getUserNameByGroupName(){
        const {data: res} = await this.$http.get(`group/getUserNames/${this.createPlanForm.groupName}`);
        if (res.status !== 200){
          return this.$message.error("获取用户数据失败！");
        }
        this.personList = res.data;

      },
      //计算结束时间
      calculationEndTime(){
        var time = new Date(this.createPlanForm.startTime);
        if (this.createPlanForm.planType === '周计划'){
          //开始时间加7天
          time = time.setDate(time.getDate() + 7);
          time = new Date(time);
        }else {
          //开始时间加30天
          time = time.setDate(time.getDate() + 30);
          time = new Date(time);
        }
        var Y = time.getFullYear() + '-';
        var M = (time.getMonth()+1 < 10 ? '0'+(time.getMonth()+1) : time.getMonth()+1) + '-';
        var D = time.getDate();
        this.createPlanForm.endTime = (Y + M + D);

      },
      //刷新函数
      refresh(){
        var data = JSON.parse(window.sessionStorage.getItem('refreshData'));
        this.getPlanByGroupName(data);
      },
      //提交创建计划
      submitPlan(){
        //发送POST请求创建项目
        this.$refs.createForm.validate(async valid => {
          if (valid){
            var data = JSON.parse(window.sessionStorage.getItem('user'));
            var fd = new FormData();
            fd.append("planType",this.createPlanForm.planType);
            fd.append("groupName",this.createPlanForm.groupName);
            fd.append("userNames",JSON.stringify(this.createPlanForm.userNames));
            fd.append("startTime",this.createPlanForm.startTime);
            fd.append("endTime",this.createPlanForm.endTime);
            fd.append("planName",this.createPlanForm.planTitle);
            fd.append("planDesc",this.createPlanForm.planDesc);
            fd.append("createPlanUser",data.userName);
            const {data: res} = await this.$http.post('plan/createPlan',fd);
            if (res.status !== 200){
              return this.$message.error(res.msg);
            }
            console.log(res);
            this.dialogNewTreeVisible = false;
            this.getPlanTree();
            this.refresh();
            return this.$message.success(res.msg);
          }else {
            return this.$message.error("请填写完整表单");
          }

        });

      },
      //通过组名获取组计划（周计划或者月计划）
      async getPlanByGroupName(treeData){
        const {data: res} = await this.$http.get("plan/getPlans",{
          params: {
            weekPlanPageNum: this.weekPage.pageNum,
            weekPlanPageSize: this.weekPage.pageSize,
            monthPlanPageNum: this.monthPage.pageNum,
            monthPlanPageSize: this.monthPage.pageSize,
            groupName: treeData.label
          }
        });
        if (res.status !== 200){
          return this.$message.error(res.msg);
        }
        this.weekPlanInfo = res.data.weekPlanList;
        this.weekPage.total = res.data.weekTotal;
        this.monthPlanInfo = res.data.monthPlanList;
        this.monthPage.total = res.data.monthTotal;
      },
      //根据PlanId返回具体的计划
      async getPlanById(treeData){
        //发送get请求
        const {data: res} = await this.$http.get(`plan/getPlanById/${treeData.planId}`);
        if (res.status !== 200){
          return this.$message.error(res.msg);
        }
        console.log(res.data.planType);
        //因为后端返回的是对象,这里需要把它转化为数组
        var arry = [];
        arry.push(res.data);
        if (res.data.planType === '周计划'){
          this.weekPlanInfo = arry;
          //面板切换
          this.activeName = 'first';
        }else {
          this.monthPlanInfo = arry;
          //面板切换
          this.activeName = 'second';
        }

      },
      //点击树形列表触发
      handleNodeClick(data){
        window.sessionStorage.setItem('refreshData',JSON.stringify(data));
        if (data.label !== '我加入的组'){
          if (data.label.indexOf("计划") == -1){
            //如果点击的是组，则查找该组的所有计划
            this.getPlanByGroupName(data);
          }else {
            this.getPlanById(data)
          }
        }
      },
      //更改计划状态
      async changeStatus(planId){
        var data = JSON.parse(window.sessionStorage.getItem('user'));
        //发送put 请求
        const {data: res} = await this.$http.put(`plan/updatePlanStatus/${planId}/${data.userName}`);
        if (res.status !== 200){
          return this.$message.error(res.msg);
        }
        console.log(res);
        this.refresh();
        return this.$message.success(res.msg);

      },
      //添加总结或者更新总结
      addSummary(planId,planSummary){
        var userInformation = JSON.parse(window.sessionStorage.getItem("user"));
        if (true){
          this.$prompt('请输入计划总结:','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(async ({value}) => {
            var fd = new FormData();
            fd.append("planSummary",value);
            fd.append("planId",planId);
            fd.append("setSummaryUser",userInformation.userName);
            if(!planSummary) {
              const {data: res} = await this.$http.post('plan/updateSummary', fd);
              if (res.status !== 200){
                return this.$message.error(res.msg);
              }
              this.refresh();
              return this.$message.success("添加成功！");
            }else {
              fd.append("isUpdateSummary","更改了总结");
              const {data: res} = await this.$http.post('plan/updateSummary', fd);
              if (res.status !== 200){
                return this.$message.error(res.msg);
              }
              this.refresh();
              return this.$message.success("更改成功！");
            }

          })
        }
      },
      //周计划面板页码
      weekHandleSizeChange(newPageSize){
        this.weekPage.pageSize = newPageSize;
        this.refresh();
      },
      weekHandleCurrentChange(newPageNum){
        this.weekPage.pageNum = newPageNum;
        this.refresh();
      },
      //月计划面板页码
      monthHandleSizeChange(newPageSize){
        this.monthPage.pageSize = newPageSize;
        this.refresh();
      },
      monthHandleCurrentChange(newPageNum){
        this.monthPage.pageNum = newPageNum;
        this.refresh();
      },
      //查看计划详情
      handleShow(planStatus,planDesc,planSummary){
        this.sideBarPlanDesc = planDesc;
        this.sideBarPlanSummary = planSummary;
        this.drawer = true
        if(planStatus == '已完成'||planStatus == '未完成'){
          this.showSummary = true
        }

      },
      //显示修改计划弹窗
      showEditDialog(planId,username,planDesc,planName,startTime,endTime){
        this.editPlanForm.planId = planId;
        this.editPlanForm.editPlanDesc = planDesc;
        this.editPlanForm.planName = planName;
        this.editPlanForm.editPlanStartTime = startTime;
        this.editPlanForm.editPlanEndTime = endTime;
        this.editPlanDialog = true;

      },
      //修改计划
      async submitEditPlan(){
        var data = JSON.parse(window.sessionStorage.getItem('user'));
        //发送post请求
        var fd = new FormData();
        fd.append("planDesc",this.editPlanForm.editPlanDesc);
        fd.append("planId",this.editPlanForm.planId);
        fd.append("editPlanUser",data.userName);
        if(this.editMonthShow) {
          fd.append("startTime", this.editPlanForm.editPlanStartTime);
          fd.append("endTime", this.editPlanForm.editPlanEndTime);
        }
        fd.append("planName",this.editPlanForm.planName);
        const {data: res} = await this.$http.post('plan/updatePlanDesc',fd);
        console.log(res);
        if (res.status !== 200){
          return this.$message.error(res.msg);
        }
        this.editPlanDialog = false;
        this.refresh();
        return this.$message.success("修改成功！");
      },
      //删除计划
      async deletePlan(planId){
        const confirmResult = await this.$confirm('此操作将永久删除该计划, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => {
          return err;
        });
        //当用户确认时，则返回值为字符串：confirm
        //取消时，返回字符串cancel
        if (confirmResult !== 'confirm'){
          return this.$message.info("已取消删除")
        }
        var data = JSON.parse(window.sessionStorage.getItem('user'));
        const {data: res} = await this.$http.delete(`plan/deletePlan/${planId}/${data.userName}`);
        if (res.status !== 200){
          return this.$message.error(res.msg);
        }
        this.refresh();
        return this.$message.success("删除成功！");
      },
      dialogClear(){
        //重置表单数据
        this.$refs.createForm.resetFields();
      },
      //tab组件：切换时触发
      handleClick(tab, event) {
        if(tab.name=='second'){
          this.editMonthShow=true
        }else{
          this.editMonthShow=false
        }
      },


    },

  }
</script>
<style scoped>
  .pagination{
    margin-top: 20px;
  }
  .crumbs {
    margin: 0px 10px 0;
  }
  .sideBarPlanDesc{
    text-indent: 50px;
    font-size: 20px;
  }
  .buttonStatus{
    margin-left: 10px;
  }
  .el-button+.el-tooltip {
    margin-left: 10px;
  }


</style>
